/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, {
  useCallback,
  useState,
  useEffect,
  forwardRef,
  useImperativeHandle,
  useRef,
} from 'react';
import { connect } from 'dva';
import { Button, Col, Form, Input, Row, Select, DatePicker, message } from 'antd';
import moment from 'moment/moment';
import StandardTable from '@/components/StandardTable';
import { changePostName } from '@/utils/changePostCompanyName';
import { isLegalData } from '@/utils/utils';
import { isEmpty, cloneDeep } from 'lodash';
import { useDebounceFn } from 'ahooks';

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;
const toDay = moment()
  .startOf('day')
  .subtract(0, 'days');
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 8,
    },
    sm: {
      span: 16,
      offset: 8,
    },
    md: {
      span: 16,
    },
  },
};
const columns = [
  {
    title: '快递品牌',
    dataIndex: 'brand',
    align: 'center',
  },
  {
    title: '网点编号',
    dataIndex: 'branch_no',
    align: 'center',
  },
  {
    title: '运单号',
    dataIndex: 'waybill_no',
    align: 'center',
  },
  {
    title: '扫描员',
    align: 'center',
    render: (text, record) => `${record.cm_name}-${record.cm_phone}`,
  },
  {
    title: '扫描类型',
    dataIndex: 'waybill_type',
    align: 'center',
  },
  {
    title: '扫描类型选项',
    dataIndex: 'scan_option',
    align: 'center',
  },
  {
    title: '扫描时间',
    dataIndex: 'scan_time',
    align: 'center',
  },
  {
    title: '上传时间',
    dataIndex: 'update_time',
    align: 'center',
  },
];

// 快递品牌显示的选项，数组有多少成员，显示多少品牌。
const brands = ['all', 'sto', 'zt', 'yt', 'yd', 'jt', 'kbtc', 'ems'];

const SearchBar = Form.create()(
  forwardRef((props, ref) => {
    const { form, dispatch, scanTypeSelectList, branchInfo = {}, tableList, branchId } = props;
    const { getFieldDecorator, validateFields, setFieldsValue } = form;
    const [scanStart, setScanStart] = useState(moment(toDay.format('YYYY-MM-DD')));
    const [scanEnd, setScanEnd] = useState(moment(toDay.format('YYYY-MM-DD')));
    const [branchList, setBranchList] = useState([]);
    const [formValues, setFormValues] = useState({});
    const [brand, setBrand] = useState('all');

    useEffect(
      () => {
        if (!isEmpty(branchInfo)) {
          setBranchList(isLegalData(branchInfo[brand], []));
        }
      },
      [branchInfo, brand],
    );

    const getList = useCallback((page = 1) => {
      validateFields((err, fieldsValue) => {
        if (err) return;
        const {
          start_scan_time,
          end_scan_time,
          waybill_no,
          courier,
          branch_code,
          scanType,
        } = fieldsValue;
        const values = cloneDeep(fieldsValue);
        values.start_scan_time = start_scan_time.format('YYYY-MM-DD 00:00:00');
        values.end_scan_time = end_scan_time.format('YYYY-MM-DD 23:59:59');
        values.waybill_no = waybill_no ? waybill_no.replace(/[\n,]/g, ',') : '';

        const inMonth = end_scan_time.month() == start_scan_time.month();

        if (moment(start_scan_time) > moment(end_scan_time)) {
          message.warn('扫描开始日期不能大于扫描结束日期！');
          return;
        }

        if (!inMonth) {
          message.warn('不支持跨月查询，请重新选择查询区间');
          return;
        }

        if (courier) {
          if (new RegExp('^[0-9]+$').test(courier)) {
            if (new RegExp('^1[3-9][0-9][0-9]{8}$').test(courier)) {
              values.cm_phone = courier;
            } else {
              message.warning('手机号码格式有误');
              // eslint-disable-next-line consistent-return
              return false;
            }
          } else {
            values.cm_name = courier;
          }
          delete values.courier;
        }
        if (branch_code == '暂无数据') {
          values.branch_code = 'all';
        } else {
          // eslint-disable-next-line prefer-destructuring
          values.branch_code = branch_code.split('-')[0];
        }
        if (scanType == '全部') {
          values.scanType = 'all';
        }
        setFormValues(values);
        dispatch({
          type: 'scan/getScanRecordsList',
          payload: {
            page,
            pageSize: 20,
            branch_id: branchId || undefined,
            ...values,
          },
        });
      });
    }, []);

    useImperativeHandle(
      ref,
      () => ({
        search: getList,
      }),
      [],
    );

    useEffect(() => {
      getList();
      dispatch({
        type: 'allocation/getBranchInfo',
        payload: {
          brand: 'all',
          branch_id: branchId || undefined,
        },
      });
    }, []);

    const { run: search } = useDebounceFn(
      (e, page = 1) => {
        e.persist();
        getList(page);
      },
      {
        wait: 300,
        leading: true,
        trailing: false,
      },
    );

    const scanTypeSelect = useCallback(visible => {
      if (visible) {
        dispatch({
          type: 'scan/getScanType',
          payload: {
            branch_id: branchId || undefined,
          },
        });
      }
    }, []);

    const download = useCallback(
      () => {
        if (tableList == 0) {
          message.error('暂无可下载数据');
          return;
        }
        const data = formValues;
        data.n_export = 'csv';
        data.waybill_type = '2';
        data.send_status = '3';
        if (branchId || branchId == 0) {
          data.branch_id = branchId;
        }
        dispatch({
          type: 'scan/getScanRecordsList',
          payload: data,
        });
      },
      [formValues, tableList],
    );

    const { run: downloadExcel } = useDebounceFn(
      () => {
        download();
      },
      {
        wait: 500,
        leading: true,
        trailing: false,
      },
    );

    const onBrandChange = useCallback(selectedBrand => {
      setBrand(selectedBrand);
      setFieldsValue({
        branch_code: 'all',
      });
    }, []);

    return (
      <Form {...formItemLayout}>
        <Row type="flex">
          <Col xs={24} sm={8} md={8} lg={8} xl={8}>
            <Row>
              <Col span={24}>
                <FormItem label="扫描开始日期">
                  {getFieldDecorator('start_scan_time', {
                    initialValue: scanStart,
                  })(
                    <DatePicker
                      allowClear={false}
                      style={{ width: '100%' }}
                      placeholder="扫描开始日期"
                      onChange={value => setScanStart(value)}
                      disabledDate={current => current && current > moment(scanEnd).endOf('day')}
                    />,
                  )}
                </FormItem>
              </Col>
              <Col span={24}>
                <FormItem label="快递品牌">
                  {getFieldDecorator('brand', {
                    initialValue: 'all',
                  })(
                    <Select placeholder="请选择快递品牌" onChange={onBrandChange}>
                      {brands.map(val => (
                        <Option key={val} value={val}>
                          {changePostName(val, 'brand')}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </FormItem>
              </Col>
              <Col span={24}>
                <FormItem label="扫描类型">
                  {getFieldDecorator('scanType', {
                    initialValue: '全部',
                  })(
                    <Select onDropdownVisibleChange={scanTypeSelect} placeholder="请选择扫描类型">
                      {scanTypeSelectList.map(val => (
                        <Option key={val.scan_type} value={val.scan_type}>
                          {val.scan_type}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </FormItem>
              </Col>
            </Row>
          </Col>
          <Col xs={24} sm={8} md={8} lg={8} xl={8}>
            <Row>
              <Col>
                <FormItem label="扫描结束日期">
                  {getFieldDecorator('end_scan_time', {
                    initialValue: scanEnd,
                  })(
                    <DatePicker
                      allowClear={false}
                      style={{ width: '100%' }}
                      placeholder="扫描结束日期"
                      onChange={value => setScanEnd(value)}
                      disabledDate={current => current && current >= moment().endOf('day')}
                    />,
                  )}
                </FormItem>
              </Col>
              <Col>
                <FormItem label="网点编号">
                  {getFieldDecorator('branch_code', {
                    initialValue: branchList.length === 0 ? '暂无数据' : 'all',
                  })(
                    <Select placeholder="请选择网点编号">
                      {branchList.length === 0 ? (
                        <Option key="none">暂无数据</Option>
                      ) : (
                        branchList.map(val => (
                          <Option key={val} value={val}>
                            {changePostName(val)}
                          </Option>
                        ))
                      )}
                    </Select>,
                  )}
                </FormItem>
              </Col>
              <Col>
                <FormItem label="扫描员">
                  {getFieldDecorator('courier')(
                    <Input placeholder="请输入扫描员手机号或姓名" allowClear />,
                  )}
                </FormItem>
              </Col>
            </Row>
          </Col>
          <Col xs={24} sm={8} md={8} lg={8} xl={8}>
            <Row>
              <Col>
                <FormItem label="运单编号" style={{ marginBottom: 0 }}>
                  {getFieldDecorator('waybill_no')(
                    <TextArea
                      allowClear
                      style={{ height: '113px', resize: 'none' }}
                      placeholder="请输入运单编号，多个运单编号用回车分隔"
                    />,
                  )}
                </FormItem>
              </Col>
              <Col>
                <FormItem {...tailFormItemLayout}>
                  <Row type="flex">
                    <Col>
                      <Button
                        icon="search"
                        type="primary"
                        onClick={search}
                        style={{ marginRight: 20 }}
                      >
                        查询
                      </Button>
                    </Col>
                    <Col>
                      <Button icon="download" type="primary" onClick={downloadExcel}>
                        下载
                      </Button>
                    </Col>
                  </Row>
                </FormItem>
              </Col>
            </Row>
          </Col>
        </Row>
      </Form>
    );
  }),
);

const ScanRecords = props => {
  const {
    dispatch,
    scanRecordsList,
    loading,
    siteNumberList,
    scanTypeSelectList,
    branchInfo,
    userInfo,
    options: { key },
  } = props;
  const isZyAccount = key == 'post';
  const { branchId } = userInfo;

  const searchRef = useRef();

  const onTableChage = useCallback(pagination => {
    const { current } = pagination;
    searchRef.current.search(current);
  }, []);

  const { run } = useDebounceFn(
    pagination => {
      onTableChage(pagination);
    },
    {
      wait: 300,
      leading: true,
      trailing: false,
    },
  );

  return (
    <div>
      <SearchBar
        wrappedComponentRef={form => {
          searchRef.current = form;
        }}
        dispatch={dispatch}
        siteNumberList={siteNumberList}
        scanTypeSelectList={scanTypeSelectList}
        branchInfo={branchInfo}
        tableList={scanRecordsList.list.length}
        {...(isZyAccount ? { branchId } : {})}
      />
      <StandardTable
        data={scanRecordsList}
        columns={columns}
        rowKey={record => record.id}
        pagination={false}
        loading={loading}
        onChange={run}
      />
    </div>
  );
};

export default connect(({ loading, scan, allocation, user, setting }) => ({
  scanRecordsList: scan.scanRecordsList,
  siteNumberList: scan.siteNumberList,
  scanTypeSelectList: scan.scanTypeSelectList,
  branchInfo: allocation.allBranchInfo,
  userInfo: user.currentUser.user_info,
  loading: loading.effects['scan/getScanRecordsList'],
  ...setting,
}))(React.memo(ScanRecords));
